
#include "../libpatches.h"
#include "seq.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

static void module_seq_processor(module m);
void module_seq_customizer(module m, char * name, char * value);

void module_seq_initializer(module m) {
	make_outputs(m, 1);
	m->output_names[0] = "out";
	m->customizer = module_seq_customizer;
	m->processor = module_seq_processor;
}

void module_seq_customizer(module m, char * name, char * value) {
	customizer_count_inputs_only(m, name, value);
	make_named_inputs(m, m->input_count * 2, 1);
	m->input_names[0] = "in";
}

static void module_seq_processor(module m) {
	output o = m->outputs[0];
	input in = m->named_inputs[0];

	input * i = m->inputs;
	int count;

	sample dur;

	sample total;
	sample n; /* value of in wrapped between 0 and 1 */
	sample sn; /* input scaled to total */

	/* first we need the total of the inputs.
	 * each segment has a duration of d/total
	 */

	for (
		total = 0,
		i = m->inputs + 1,
		count = m->input_count;
		count;
		i += 2,
		count -= 2
	) total += fabs(***i);

	/* now we'll scale phase up to total */
	n = **in;
	n -= floor(n);
	sn = n * total;

	/* now we'll figure out which segment we're in */

	sample next;
	sample last;
	sample min;
	next = 0;
	last = 0;
	for (count = 0; count < m->input_count; count += 2) {
		last = next;
		dur = fabs(**(m->inputs[count + 1]));
		next = last + dur;
		min = **(m->inputs[count]);
		if (sn <= next) break;
	}

	/*
	printf("last: %f\n", last);
	printf("next: %f\n", next);
	printf("dur: %f\n", dur);
	printf("min: %f\n", min);
	printf("n: %f\n", n);
	printf("sn: %f\n", sn);
	printf("sn - last: %f\n", sn - last);
	printf("(sn - last)/dur: %f\n", (sn - last)/dur);
	printf("\n");
	*/

	*o = min;
}
